##### Compliance Game 2
##### JBS July 6 2012

# p is probability I believe any individual supports the law. 
# n is number of players

# pop is a vector of true (unknown) individual support for the law.

# Law is legit if sufficiently high fraction of population, t, supports it. 
# Threshold for society accepting law as legit. 

# Citizens always obey law if they support it and they believe society believes the law to be legit, with prob r if they support it but think society doesn't find it legit, with probably q if they think society believes law but they don't. Always disobey if they don't support law and dont think society believes law is legit either.   

comp <- function (p,n,pop,t,r,q) {

# Calculate Pr(support|compliance) using Bayes Rule. 
# Prob of Comply|individual support

# First, calculate probability that law is legit / not legit
pl <- pbinom(t*n,n,p, lower.tail=FALSE)
pnl <- pbinom(t*n,n,p)

pci <- pl+r*pnl
pc <- pci*p + q*pl*(1-p)

pric <- (pci*p)/pc

# Calc Pr(individual support|non-compliance) using Bayes Rule. 
# Pr(~comp|ind)
pnci <- (1-r)*pnl
pnc <- pnci*p + ((1-q)*(pl)+1*pnl)*(1-p)

princ <- (pnci*p)/pnc  

# If we assume simutaneous play, everyone either obeys or disobeys at once and then everyone updates beliefs about whether consensus exists. 

# First simulate behavior

pac <- ifelse(pop==1 & p>t,1,
			ifelse(pop==1 & runif(n)<r,1,
				ifelse(pop==0 & p>t & runif(n)<q,1,0)))


out <- ifelse(pac==1,pric,princ)

return(list(out=out,pop=pop,pac=pac,pric=pric,princ=princ))

}

